package cn.learn.validator.annotation;

import cn.learn.validator.ValidatorUtil;
import cn.learn.validator.exception.ListValidException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author huangyezhan
 * @version 1.0
 * @date 2020年08月13日22:49
 */
public class ValidListValidator implements ConstraintValidator<ValidList, List> {
    private Class<?>[] groups;

    @Override
    public void initialize(ValidList validList) {
        groups = validList.listGroups();

    }

    @Override
    public boolean isValid(List list, ConstraintValidatorContext context) {
        Map<Integer, Set<ConstraintViolation<Object>>> errors = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            Object                           o         = list.get(i);
            Validator                        validator = ValidatorUtil.validator;
            Set<ConstraintViolation<Object>> error     = ValidatorUtil.validator.validate(o, groups);
            if (error.size() > 0) {
                System.out.println(error);
                errors.put(i + 1, error);
            }
        }
        //由于这个是个集合，所以靠抛出异常
        if (errors.size() > 0) {
            throw new ListValidException(errors);
        }
        return true;
    }

}
